package cn.zz.veggie.persistence.repository;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.springframework.stereotype.Repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.zz.comm.core.types.query.PageQuery;
import cn.zz.comm.exception.classes.FatalErrorException;
import cn.zz.comm.util.CollectorUtil;
import cn.zz.veggie.model.domain.User;
import cn.zz.veggie.model.query.UserQuery;
import cn.zz.veggie.persistence.dao.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 用户表(User)repo
 *
 * @author zhongq
 * @since 2024-04-27 13:03:53
 */
@Slf4j
@Repository
@RequiredArgsConstructor
public class UserRepository {

	private final UserMapper userMapper;

	public User findById(Integer id) {
		Objects.requireNonNull(id);
		return userMapper.selectById(id);
	}

	public Map<Integer, User> findByIds(Collection<Integer> ids) {
		if (CollectionUtil.isEmpty(ids)) {
			return Collections.emptyMap();
		}
		final List<User> records = userMapper.selectBatchIds(ids);
		return CollectorUtil.btmByKeyFun(records, User::getId);
	}

	public List<User> findByPage(UserQuery query, PageQuery page) {
		final LambdaQueryWrapper<User> queryWrapper = query.toQueryWrapper();
		final Page<User> queryPage = query.toPage(page);
		return userMapper.selectList(queryPage, queryWrapper);
	}

	public void save(User user) {
		Objects.requireNonNull(user);
		if (user.getId() == null) {
			// insert
			final int effect = userMapper.insert(user);
			if (effect != 1) {
				throw new FatalErrorException("created user fail ");
			}
			log.info("created user for {}", user.getId());
		} else {
			// update
			final int effect = userMapper.updateById(user);
			if (effect != 1) {
				throw new FatalErrorException("update user fail ");
			}
			log.info("updated user for {}", user.getId());
		}
	}

	public void deleteById(Integer id) {
		Objects.requireNonNull(id);
		final int effect = userMapper.deleteById(id);
		if (effect != 1) {
			log.error("delete");
			throw new FatalErrorException("delete user fail ");
		}
		log.info("delete user for {}", id);
	}

	public void deleteByIds(Collection<Integer> ids) {
		if (CollUtil.isEmpty(ids)) {
			return;
		}
		final int effect = userMapper.deleteByIds(ids);
		log.info("delete user for {}", effect);
	}

}